<script lang="ts" setup>
import useLoading from '@/hooks/loading'
import { TitleMap } from '@/config/constants'
import Tinymce from '@/components/Editor/tinymce.vue'
import request from '@/utils/request'
import { set } from '@vueuse/core'
import { documentView } from '@/utils'
import { useUserInfo } from '@/hooks/core/useUserInfo'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { cloneDeep } from 'lodash'

interface EditProps {
  modelForm: any
  editVisible: boolean
  createData: any
  updateData: any
  title?: string
  dialogStatus: string
  setEditVisible: any
}

const props = withDefaults(defineProps<EditProps>(), {
  editVisible: false,
  modelForm: {
    isTop: false,
    status: false,
    title: '',
    content: '',
  },
  columns: [],
  dialogStatus: 'create',
  createData: () => {},
  updateData: () => {},
  setEditVisible: () => {},
})
const { loading, setLoading } = useLoading()
const tinymceKey = ref(1)
const formRef = ref<FormInstance>()
const activeCollapse = ref(['1', '2', '3'])
const categoryOptions = ref<any>([])
const tagOptions = ref<any>([])
const tags = ref<any>([])
const { modelForm } = toRefs(props)
request.get('/category').then((res) => {
  set(categoryOptions, res.rows)
})

request.get('/tags').then((res) => {
  set(tagOptions, res.rows)
})
;[1, 2, 3].forEach((item) => item)
// 关闭
const handleClose = () => {
  props.setEditVisible()
  formRef.value!.resetFields()
  modelForm.value.content = ''
  modelForm.value.tags = ''
  modelForm.value.status = false
  set(tags, [])
}

// 分类变化
const onChangeCategory = (value: any) => {
  modelForm.value.categoryId = value
}

// 处理标签
const handleTags = (checked: any) => {
  const selectedTags = tagOptions.value.filter((t: any) => checked.includes(t.id))
  const tags = selectedTags.map((t: any) => ({ articleId: modelForm.value.id, tagName: t.tagName, id: t.id }))
  modelForm.value.tags = tags
}

// 标签变化
const onChangeTags = (value: any) => {
  set(tags, value)
  handleTags(value)
}

// 发布
const onSave = () => {
  formRef
    .value!.validate((valid: any) => {
      if (valid) return

      const data = cloneDeep(unref(modelForm))

      data.isTop = typeof data.isTop !== 'undefined' ? +data.isTop : 0
      data.status = typeof data.status !== 'undefined' ? +!data.status : 1
      data.userId = useUserInfo()?.id

      delete data.category

      props.dialogStatus === 'create' ? props.createData(data) : props.updateData(data)

      handleClose()
    })
    .catch((error: any) => {
      console.log('error', error)
    })
    .finally(() => {
      setLoading(false)
    })

  return false
}

// 预览
const onPreview = () => {
  const content = modelForm.value.content
  documentView({ content })
}
// 关闭
const onClose = () => {
  handleClose()
}

// 修改时标签选中
watch(
  () => props.modelForm,
  (val) => {
    if (val && Array.isArray(val.tags)) {
      tags.value = val.tags?.map((t: any) => t.id)
    }
  },
  { deep: true, immediate: true }
)

const visible = ref(false)
watch(
  () => props.editVisible,
  (show) => {
    visible.value = show
  }
)

onActivated(() => {
  tinymceKey.value++
})
</script>
<template>
  <a-modal v-model:visible="visible" @cancel="handleClose" draggable :loading="loading" fullscreen :footer="false">
    <template #title>{{ TitleMap[dialogStatus] }}</template>
    <a-alert hidden title="文明发言" type="warning" class="mb-5" :closable="true" />
    <a-form ref="formRef" :model="modelForm" auto-label-width>
      <a-row :gutter="40">
        <a-col :span="17">
          <a-form-item field="id" hidden>
            <input type="hidden" name="id" :value="modelForm.id" />
          </a-form-item>
          <a-row :gutter="20">
            <a-col :span="12">
              <a-form-item label="上级分类" field="categoryId" :rules="[{ required: true, message: '请选择类别' }]" :validate-trigger="['change', 'blur']">
                <!-- <a-select v-model="modelForm.categoryId" placeholder="请选择类别" @change="onChangeCategory">
                  <a-option v-for="item in categoryOptions" :key="item.id" :label="item.title" :value="item.id" />
                </a-select> -->
                <a-tree-select :model-value="modelForm.categoryId" :data="categoryOptions" :field-names="{ key: 'id', title: 'title' }" @change="onChangeCategory" placeholder="请选择类别" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="标签" field="tags" :rules="[{ required: true, message: '请选择标签' }]" :validate-trigger="['change', 'blur']">
                <a-select v-model="tags" placeholder="请选择标签" multiple :limit="5" allow-clear @change="onChangeTags">
                  <a-option v-for="item in tagOptions" :key="item.id" :label="item.tagName" :value="item.id" />
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item label="标题" field="title" :rules="[{ required: true, message: '请输入标题' }]" :validate-trigger="['change', 'blur']">
            <a-input v-model="modelForm.title" placeholder="请输入标题" />
          </a-form-item>
          <a-form-item label="内容" field="content" :rules="[{ required: true, message: '请输入内容' }]" :validate-trigger="['change', 'blur']">
            <Tinymce :key="tinymceKey" v-model:value="modelForm.content" width="100%" />
          </a-form-item>
        </a-col>

        <a-col :span="7">
          <a-space :size="15" class="mb-4">
            <a-button type="primary" @click="onSave">发布</a-button>
            <a-button @click="onPreview">预览</a-button>
            <a-button @click="onClose">关闭</a-button>
          </a-space>
          <a-collapse :default-active-key="activeCollapse" :bordered="false" expand-icon-position="right">
            <a-collapse-item header="文章状态" key="1">
              <a-row>
                <a-col :span="7"><a-checkbox v-model="modelForm.isTop">是否置顶</a-checkbox></a-col>
                <a-col :span="7"><a-checkbox v-model="modelForm.status">保存草稿</a-checkbox></a-col>
              </a-row>
            </a-collapse-item>
            <a-collapse-item header="缩略图" key="2"> 2222 </a-collapse-item>
            <a-collapse-item header="摘要" key="3">
              <a-form-item field="summary" no-style>
                <a-textarea v-model="modelForm.summary" :rows="3" allow-clear show-word-limit auto-size />
              </a-form-item>
            </a-collapse-item>
          </a-collapse>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>
<style lang="scss"></style>
